#!/usr/bin/env python3
"""
AWS Lambda 入口函数
由 Kinesis Event Source Mapping 自动触发

事件格式：
{
    "Records": [
        {
            "kinesis": {
                "data": "base64_encoded_json",
                "sequenceNumber": "...",
                "partitionKey": "userId",
                ...
            },
            "eventID": "...",
            "eventName": "aws:kinesis:record",
            ...
        }
    ]
}
"""

import json
import base64
import logging
from typing import Dict, Any, List

# 导入核心模块
from core import BehaviorAnalyzer
from database import write_to_postgres_batch

# 配置日志
logger = logging.getLogger()
logger.setLevel(logging.INFO)

# 全局初始化（Lambda 容器复用）
analyzer = BehaviorAnalyzer()
logger.info("✅ BehaviorAnalyzer 已初始化")


def lambda_handler(event: Dict[str, Any], context) -> Dict[str, Any]:
    """
    Lambda 函数入口

    Args:
        event: Kinesis 事件数据
        context: Lambda 上下文对象

    Returns:
        响应对象
    """
    try:
        # 解析 Kinesis 记录
        records = event.get('Records', [])
        logger.info(f"📥 收到 {len(records)} 条 Kinesis 记录")

        if not records:
            return {
                'statusCode': 200,
                'body': json.dumps('No records to process')
            }

        # 批量处理
        results = []
        for record in records:
            try:
                # 解码 Kinesis 数据
                kinesis_data = record['kinesis']['data']
                decoded_data = base64.b64decode(kinesis_data).decode('utf-8')
                event_data = json.loads(decoded_data)

                # 调用核心分析逻辑
                analysis_result = analyzer.analyze(event_data)

                # 收集结果
                results.append((event_data, analysis_result))

                logger.info(
                    f"✨ 分析完成: {event_data.get('userId')} - "
                    f"{analysis_result['behavior_type']}"
                )

            except Exception as e:
                logger.error(f"❌ 处理单条记录失败: {e}", exc_info=True)
                # 继续处理其他记录

        # 批量写入数据库
        if results:
            write_to_postgres_batch(results)
            logger.info(f"✅ 成功处理 {len(results)} 条记录")

        return {
            'statusCode': 200,
            'body': json.dumps({
                'message': f'Processed {len(results)} events',
                'processed': len(results),
                'total': len(records)
            })
        }

    except Exception as e:
        logger.error(f"❌ Lambda 函数执行失败: {e}", exc_info=True)
        return {
            'statusCode': 500,
            'body': json.dumps({'error': str(e)})
        }


def parse_kinesis_record(record: Dict[str, Any]) -> Dict[str, Any]:
    """
    解析单条 Kinesis 记录

    Args:
        record: Kinesis 记录

    Returns:
        解析后的事件数据
    """
    kinesis_data = record['kinesis']['data']
    decoded_data = base64.b64decode(kinesis_data).decode('utf-8')
    return json.loads(decoded_data)
